<template>
  <view class="container">
    <!-- 分类标题 -->
    <view v-if="categoryName" class="category-title">
      <text>{{ categoryName }}</text>
    </view>
    
    <!-- 顶部搜索栏 -->
    <view class="header">
      <view class="search-container">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input 
          class="search-input" 
          type="text" 
          placeholder="奥特曼" 
          v-model="searchKeyword"
          @confirm="searchGoods"
          @input="handleSearchInput"
        />
      </view>
      <view class="header-actions">
        <view class="view-toggle" @click="toggleViewMode">
          <image 
            :src="viewMode === 'grid' ? '/static/shenghuojiadian/切换1.png' : '/static/shenghuojiadian/切换2.png'" 
            class="toggle-icon"
            mode="aspectFit"
            @error="handleImageError"
          ></image>
        </view>

        <view class="divider"></view>
        <view class="target-btn">
          <uni-icons type="location" size="18" color="#333"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 排序筛选栏 -->
    <view class="sort-filter-bar">
      <view 
        class="sort-item" 
        :class="{ active: currentSort === 'comprehensive' }"
        @click="setSort('comprehensive')"
      >
        综合排序
      </view>
      <view 
        class="sort-item" 
        :class="{ active: currentSort === 'sales' }"
        @click="setSort('sales')"
      >
        销量
        <view v-if="currentSort === 'sales'" class="sort-arrow">
          <text v-if="salesOrder === 'asc'">↑</text>
          <text v-else>↓</text>
        </view>
      </view>
      <view 
        class="sort-item" 
        :class="{ active: currentSort === 'price' }"
        @click="setSort('price')"
      >
        价格
        <view v-if="currentSort === 'price'" class="sort-arrow">
          <text v-if="priceOrder === 'asc'">↑</text>
          <text v-else>↓</text>
        </view>
      </view>
      <view 
        class="sort-item filter-btn" 
        :class="{ active: showFilter }"
        @click="toggleFilter"
      >
        筛选
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-container" :class="viewMode">
      <view v-if="goodsList.length === 0 && !loading" class="no-data">
        暂无商品数据
      </view>
	   
      <view 
        class="goods-item" 
        v-for="(item, index) in goodsList" 
        :key="item.id || index"
        @click="goToDetail(item)"
      >
        <image class="goods-image" :src="item.image" mode="aspectFill"></image>
        <view class="goods-info">
          <view class="goods-title">{{ item.title }}</view>
          <view class="goods-price">¥{{ item.price.toFixed(2) }}</view>
          <view class="goods-tags">
            <text v-if="item.coupon" class="tag coupon">券</text>
            <text v-if="item.fullReduction" class="tag full-reduction">满减</text>
            <text class="sales-info">已售{{ item.sales }}</text>
          </view>
          <view class="shop-info">
            <text v-if="item.isSelfOperated" class="self-operated">自营</text>
            <text class="shop-name">{{ item.shopName }}</text>
            <text class="comment-count">{{ item.comments }}条评论</text>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      <view v-if="!loading && hasMore" class="load-more" @click="loadMore">
        <text>加载更多</text>
      </view>
      <view v-if="!loading && !hasMore && goodsList.length > 0" class="no-more">
        <text>没有更多数据了</text>
      </view>
    </view>

    <!-- 筛选侧边栏 -->
    <view v-if="showFilter" class="filter-overlay" @click="closeFilter">
      <view class="filter-panel" @click.stop>
        <view class="filter-header">
          <text class="filter-title">筛选条件</text>
          <view class="filter-close" @click="closeFilter">
            <uni-icons type="close" size="20" color="#999"></uni-icons>
          </view>
        </view>

        <!-- 全部分类 -->
        <view class="filter-section">
          <view class="section-title">全部分类</view>
          <view class="filter-options">
            <view 
              class="filter-option" 
              v-for="(category, index) in categories" 
              :key="index"
              :class="{ selected: selectedCategories.includes(category) }"
              @click="toggleCategory(category)"
            >
              {{ category }}
            </view>
          </view>
        </view>

        <!-- 价格区间 -->
        <view class="filter-section">
          <view class="section-title">价格区间</view>
          <view class="price-range">
            <input 
              class="price-input" 
              type="number" 
              placeholder="最低价" 
              v-model="priceRange.min"
            />
            <text class="price-separator">-</text>
            <input 
              class="price-input" 
              type="number" 
              placeholder="最高价" 
              v-model="priceRange.max"
            />
          </view>
        </view>

        <!-- 筛选按钮 -->
        <view class="filter-actions">
          <button class="reset-btn" @click="resetFilter">重置</button>
          <button class="confirm-btn" @click="applyFilter">确定</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { get } from '@/config/request.js'

export default {
  data() {
    return {
      // 搜索
      searchKeyword: '',
      
      // 分类相关
      categoryId: null, // 分类ID
      categoryName: '', // 分类名称
      
      // 视图模式
      viewMode: 'list', // 'list' 或 'grid'
      
      // 排序
      currentSort: 'comprehensive',
      salesOrder: 'desc',
      priceOrder: 'asc',
      
      // 筛选
      showFilter: false,
      categories: [],
      selectedCategories: [],
      priceRange: {
        min: '',
        max: ''
      },
      
      // 分页相关
      pageNum: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      hasMore: true,
      
      // 定时器
      searchTimer: null,
      
      // 商品数据
      goodsList: []
    }
  },
  
  computed: {
    // 可以添加其他计算属性
  },
  
  onLoad(options) {
    // 接收传递的参数
    if (options.categoryId) {
      this.categoryId = parseInt(options.categoryId)
      this.categoryName = options.categoryName || ''
      console.log('接收到的分类ID:', this.categoryId, '分类名称:', this.categoryName)
    }
    
    // 初始化数据
    this.initData()
  },
  
  mounted() {
    console.log('页面加载完成，商品数据:', this.goodsList)
  },
  
  beforeDestroy() {
    // 清理定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer)
    }
  },
  
  methods: {
    // 初始化数据
    async initData() {
      try {
        // 如果有分类ID，获取该分类下的商品
        if (this.categoryId) {
          await this.fetchGoodsByCategory()
        } else {
          // 获取所有商品列表
          await this.fetchGoodsList()
        }
        
        // 获取分类数据用于筛选
        await this.fetchCategories()
      } catch (error) {
        console.error('初始化数据失败:', error)
      }
    },
    
    // 根据分类ID获取商品
    async fetchGoodsByCategory() {
      if (this.loading) return
      
      this.loading = true
      
      try {
        console.log('开始获取分类商品，分类ID:', this.categoryId)
        
        const response = await get('/shangpin/platform/list', {
          categoryId: this.categoryId,
          status: 1, // 上架状态
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
        
        console.log('分类商品接口响应:', response)
        
        if (response.code === 200 && response.rows) {
          // 将后端字段映射到前端字段
          const mappedGoods = response.rows.map(product => ({
            id: product.id,
            title: product.productName,
            price: product.price || 0,
            image: product.mainImage || product.thumbnail || '/static/shenghuojiadian/小丸子.jpg',
            coupon: true, // 默认显示优惠券标签
            fullReduction: true, // 默认显示满减标签
            sales: product.soldNum || 0,
            isSelfOperated: true, // 默认自营
            shopName: '杂货铺进店>',
            comments: 0,
            category: this.categoryName
          }))
          
          if (this.pageNum === 1) {
            this.goodsList = mappedGoods
          } else {
            this.goodsList = [...this.goodsList, ...mappedGoods]
          }
          
          this.total = response.total || 0
          this.hasMore = this.goodsList.length < this.total
          
          console.log('处理后的商品数据:', this.goodsList)
        } else {
          console.error('获取分类商品失败:', response.msg)
          this.goodsList = []
          this.hasMore = false
        }
      } catch (error) {
        console.error('获取分类商品异常:', error)
        uni.showToast({
          title: '获取商品列表失败',
          icon: 'none'
        })
        this.goodsList = []
        this.hasMore = false
      } finally {
        this.loading = false
      }
    },
    
    // 获取分类数据
    async fetchCategories() {
      try {
        console.log('开始获取分类数据...')
        
        const response = await get('/shangpin/classify/list', {
          status: 'enabled'
        })
        
        console.log('分类接口响应:', response)
        
        if (response.code === 200 && response.rows) {
          this.categories = response.rows.map(category => category.categoryName)
          console.log('获取到的分类:', this.categories)
        }
      } catch (error) {
        console.error('获取分类失败:', error)
      }
    },
    
    // 获取商品列表
    async fetchGoodsList(isLoadMore = false) {
      if (this.loading) return
      
      this.loading = true
      
      try {
        console.log('开始获取商品列表...')
        
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          status: 1
        }
        
        // 如果有搜索关键词，添加到参数中
        if (this.searchKeyword.trim()) {
          params.productName = this.searchKeyword.trim()
        }
        
        console.log('商品列表请求参数:', params)
        
        const response = await get('/shangpin/platform/list', params)
        
        console.log('商品列表接口响应:', response)
        
        if (response.code === 200 && response.rows) {
          // 将后端字段映射到前端字段
          const mappedGoods = response.rows.map(product => ({
            id: product.id,
            title: product.productName,
            price: product.price || 0,
            image: product.mainImage || product.thumbnail || '/static/shenghuojiadian/小丸子.jpg',
            coupon: true,
            fullReduction: true,
            sales: product.soldNum || 0,
            isSelfOperated: true,
            shopName: '杂货铺进店>',
            comments: 0,
            category: '数码办公'
          }))
          
          if (isLoadMore) {
            this.goodsList = [...this.goodsList, ...mappedGoods]
          } else {
            this.goodsList = mappedGoods
          }
          
          this.total = response.total || 0
          this.hasMore = this.goodsList.length < this.total
          
          console.log('处理后的商品数据:', this.goodsList)
        } else {
          console.error('获取商品列表失败:', response.msg)
          this.goodsList = []
          this.hasMore = false
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        uni.showToast({
          title: '获取商品列表失败',
          icon: 'none'
        })
        this.goodsList = []
        this.hasMore = false
      } finally {
        this.loading = false
      }
    },
    
    // 搜索商品
    async searchGoods() {
      console.log('开始搜索商品:', this.searchKeyword)
      this.pageNum = 1
      if (this.categoryId) {
        await this.fetchGoodsByCategory()
      } else {
        await this.fetchGoodsList()
      }
    },
    
    // 加载更多
    async loadMore() {
      if (!this.hasMore || this.loading) return
      
      console.log('开始加载更多商品...')
      this.pageNum++
      if (this.categoryId) {
        await this.fetchGoodsByCategory()
      } else {
        await this.fetchGoodsList(true)
      }
    },
    
    // 切换视图模式
    toggleViewMode() {
      this.viewMode = this.viewMode === 'list' ? 'grid' : 'list'
      console.log('切换视图模式:', this.viewMode)
    },
    
    // 设置排序
    async setSort(type) {
      console.log('设置排序:', type)
      
      if (type === 'comprehensive') {
        this.currentSort = 'comprehensive'
      } else if (type === 'sales') {
        if (this.currentSort === 'sales') {
          this.salesOrder = this.salesOrder === 'asc' ? 'desc' : 'asc'
        } else {
          this.currentSort = 'sales'
          this.salesOrder = 'desc'
        }
      } else if (type === 'price') {
        if (this.currentSort === 'price') {
          this.priceOrder = this.priceOrder === 'asc' ? 'desc' : 'asc'
        } else {
          this.currentSort = 'price'
          this.priceOrder = 'asc'
        }
      }
      
      // 重新获取数据
      this.pageNum = 1
      if (this.categoryId) {
        await this.fetchGoodsByCategory()
      } else {
        await this.fetchGoodsList()
      }
    },
    
    // 切换筛选面板
    toggleFilter() {
      this.showFilter = !this.showFilter
    },
    
    // 关闭筛选面板
    closeFilter() {
      this.showFilter = false
    },
    
    // 切换分类选择
    toggleCategory(category) {
      const index = this.selectedCategories.indexOf(category)
      if (index > -1) {
        this.selectedCategories.splice(index, 1)
      } else {
        this.selectedCategories.push(category)
      }
    },
    
    // 重置筛选
    resetFilter() {
      this.selectedCategories = []
      this.priceRange.min = ''
      this.priceRange.max = ''
    },
    
    // 应用筛选
    async applyFilter() {
      this.showFilter = false
      console.log('应用筛选条件:', {
        categories: this.selectedCategories,
        priceRange: this.priceRange
      })
      
      // 重新获取数据
      this.pageNum = 1
      if (this.categoryId) {
        await this.fetchGoodsByCategory()
      } else {
        await this.fetchGoodsList()
      }
    },
    
    // 跳转到商品详情 - 跳转到goumaishangpin页面
    goToDetail(item) {
      console.log('跳转到商品详情:', item)
      console.log('商品ID:', item.id)
      
      if (!item.id) {
        console.error('商品ID不存在:', item)
        uni.showToast({
          title: '商品信息不完整',
          icon: 'none'
        })
        return
      }
      
      // 跳转到goumaishangpin页面，传递商品ID
      uni.navigateTo({
        url: `/pages/goumaishangpin/goumaishangpin?id=${item.id}`,
        success: () => {
          console.log('成功跳转到商品详情页面，商品ID:', item.id)
        },
        fail: (error) => {
          console.error('跳转失败:', error)
          uni.showToast({
            title: '页面跳转失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 处理图片加载错误
    handleImageError(e) {
      console.log('图片加载失败:', e)
    },
    
    // 处理搜索输入
    handleSearchInput() {
      // 防抖处理
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      this.searchTimer = setTimeout(() => {
        this.searchGoods()
      }, 500)
    }
  }
}
</script>

<style scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 分类标题 */
.category-title {
  background-color: #fff;
  padding: 15px;
  border-bottom: 1px solid #eee;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* 顶部搜索栏 */
.header {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}



.search-container {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 20px;
  padding: 8px 15px;
  margin-right: 10px;
  max-width: 200px;
}

.search-input {
  flex: 1;
  margin-left: 8px;
  font-size: 14px;
  color: #333;
  border: none;
  background: transparent;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
  min-width: 80px;
  position: relative;
  z-index: 10;
}

.view-toggle, .target-btn {
  padding: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 24px;
  min-height: 24px;
  position: relative;
  z-index: 11;
}

.view-toggle {
  background-color: transparent;
  border: none;
  outline: none;
}

.toggle-icon {
  width: 18px;
  height: 18px;
}

.divider {
  width: 1px;
  height: 20px;
  background-color: #ddd;
}

/* 排序筛选栏 */
.sort-filter-bar {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.sort-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px 0;
  font-size: 14px;
  color: #666;
  position: relative;
}

.sort-item.active {
  color: #ff4444;
  font-weight: 500;
}

.sort-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 2px;
  background-color: #ff4444;
}

.filter-btn {
  border-left: 1px solid #eee;
}

.sort-arrow {
  margin-left: 4px;
  color: #ff4444;
  font-size: 12px;
}

/* 商品列表 */
.goods-container {
  padding: 10px;
  min-height: 200px;
}

.no-data {
  text-align: center;
  color: #999;
  font-size: 14px;
  padding: 50px 0;
}

.loading, .load-more, .no-more {
  text-align: center;
  padding: 20px 0;
  color: #999;
  font-size: 14px;
}

.load-more {
  cursor: pointer;
  color: #666;
}

.load-more:hover {
  color: #333;
}

.goods-container.list .goods-item {
  display: flex;
  background-color: #fff;
  margin-bottom: 10px;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.goods-container.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.goods-container.grid .goods-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.goods-image {
  width: 120px;
  height: 120px;
  border-radius: 6px;
  object-fit: cover;
  flex-shrink: 0;
}

.goods-container.grid .goods-image {
  width: 100%;
  height: 150px;
}

.goods-info {
  flex: 1;
  margin-left: 12px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-container.grid .goods-info {
  margin-left: 0;
  margin-top: 8px;
}

.goods-title {
  font-size: 14px;
  color: #333;
  line-height: 1.4;
  margin-bottom: 6px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.goods-price {
  font-size: 16px;
  color: #ff4444;
  font-weight: 500;
  margin-bottom: 6px;
}

.goods-tags {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
}

.tag {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 3px;
  color: #fff;
}

.tag.coupon {
  background-color: #ff9800;
}

.tag.full-reduction {
  background-color: #ff5722;
}

.sales-info {
  font-size: 12px;
  color: #999;
}

.shop-info {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
}

.self-operated {
  color: #ff4444;
  border: 1px solid #ff4444;
  padding: 1px 4px;
  border-radius: 2px;
}

.shop-name {
  color: #666;
}

.comment-count {
  color: #999;
}

/* 筛选面板 */
.filter-overlay {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  justify-content: flex-end;
}

.filter-panel {
  width: 80%;
  max-width: 320px;
  background-color: #fff;
  height: 100%;
  overflow-y: auto;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.filter-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.filter-close {
  padding: 5px;
}

.filter-section {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.section-title {
  font-size: 15px;
  font-weight: 500;
  color: #333;
  margin-bottom: 12px;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-option {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 16px;
  font-size: 13px;
  color: #666;
  background-color: #fff;
  transition: all 0.2s;
}

.filter-option.selected {
  border-color: #ff4444;
  color: #ff4444;
  background-color: rgba(255, 68, 68, 0.1);
}

.price-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.price-input {
  flex: 1;
  height: 36px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 10px;
  font-size: 14px;
}

.price-separator {
  color: #999;
  font-size: 14px;
}

.filter-actions {
  display: flex;
  padding: 15px;
  gap: 10px;
}

.reset-btn, .confirm-btn {
  flex: 1;
  height: 40px;
  border-radius: 4px;
  font-size: 15px;
  border: none;
}

.reset-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background: linear-gradient(135deg, #ff6b35, #f7931e);
  color: #fff;
}
</style>
